/**
 * MementoSupport.java
 * 20/05/2011 17:35:49
 */
package model.memento;

import java.util.Stack;

import javax.swing.undo.UndoableEdit;
import javax.swing.undo.UndoableEditSupport;

/**
 * @author walber
 * 
 */
public class MementoSupport extends UndoableEditSupport {

	private Stack<PieceUndoableEdit> edits;

	private boolean notificationSuspended;

	public MementoSupport() {
		super();
		this.notificationSuspended = false;
	}

	/**
	 * @param notificationSuspended
	 *            the notificationSuspended to set
	 */
	public void setNotificationSuspended(boolean notificationSuspended) {
		this.notificationSuspended = notificationSuspended;
	}

	/**
	 * @see javax.swing.undo.UndoableEditSupport#beginUpdate()
	 */
	@Override
	public synchronized void beginUpdate() {
		this.edits = new Stack<PieceUndoableEdit>();
		super.beginUpdate();
	}

	/**
	 * @see javax.swing.undo.UndoableEditSupport#postEdit(javax.swing.undo.UndoableEdit)
	 */
	@Override
	public synchronized void postEdit(UndoableEdit e) {
		if (this.notificationSuspended == false) {
			// super.postEdit(e);
			this.edits.push((PieceUndoableEdit) e);
		}
	}

	/**
	 * @see javax.swing.undo.UndoableEditSupport#endUpdate()
	 */
	@Override
	public synchronized void endUpdate() {
		if (isInProgress() && edits != null) {
			while (edits.isEmpty() == false) {
				super.postEdit(edits.pop());
			}
			this.edits = null;
			super.endUpdate();
		}
	}

	/**
	 * Si Esta abierta la edicion del compoundEdit actual.
	 * 
	 * @return boolean
	 */
	public boolean isInProgress() {
		return this.compoundEdit != null && this.compoundEdit.isInProgress()
				&& this.notificationSuspended == false;
	}

	/**
	 * Terminar el compoundEdit sin notificar a los listeners.
	 */
	public synchronized void die() {
		this.updateLevel = 0;
		this.compoundEdit.end();
		this.compoundEdit.die();
		this.compoundEdit = null;
		this.edits = null;
	}
}
